package testDay;

public class day1_3 {
    public String addBinary(String a, String b) {
        /*
         * 1.比较字符串长度，短的左位补0
         * 2.设置进位，从右向左逐位相加，满2进1,最后判断标志位是否为1，若为一结果加”1“
         * 3.结果保存在StringBuffer中，倒序输出
         */
        StringBuffer res = new StringBuffer();
        int carry = 0;
        //比较a，b长度
        while (a.length() != b.length()) {
            if (a.length() < b.length()) {
                a = "0" + a;
            } else {
                b = "0" + b;
            }
        }
        for (int i = a.length() - 1; i >= 0; i--) {
            //取出每位的值转成Integer型
            int aValue = Integer.valueOf(a.charAt(i)) - 48;
            int bValue = Integer.valueOf(b.charAt(i)) - 48;
/*            System.out.print(aValue + " ");
            System.out.print(bValue + " ");
            System.out.print(carry + " ");*/
            int sum = aValue + bValue + carry;
//            System.out.println(sum + " sum");
            if (sum < 2) {
                res.append(sum);
                carry = 0;
            } else {
                res.append(sum - 2);
                carry = 1;
            }
        }
//        System.out.println(res.toString());
        //最后进位是否加1
        if (carry == 1) {
            res.append(1);
        }
        //反向输出res
        return res.reverse().toString();
    }
}
